using Sirenix.OdinInspector;
using UnityEngine;
using UnityEngine.EventSystems;
namespace WorkFlow.Tools.UI
{
    [ExecuteAlways][RequireComponent(typeof(UIBehaviourDriver))]
    [AddComponentMenu("WorkFlow/UGUI/UIBehaviour/HeightPadding")]
    public class HeightPadding  : MonoBehaviour , IUIBehaviourDriverElement
    {
        [SerializeField] int order;
        [SerializeField]RectTransform[] rectTransforms;
        [SerializeField] private float heightPadding;
        [SerializeField] bool clampHeight;
        [SerializeField] [ShowIf("clampHeight")] private Vector2Int heightRange;
        bool IUIBehaviourDriverElement.ElementEnabled => enabled;
        int IUIBehaviourDriverElement.Order => order;
        void IUIBehaviourDriverElement.OnRectTransformDimensionsChange()
        {
            Apply();
        }

        void Apply()
        {
#if UNITY_EDITOR
            _isValidate = false;
#endif
            if(transform is RectTransform rectTransform)
            {
                if (rectTransforms == null || rectTransforms.Length == 0)
                {
                    return;
                }

                foreach (var item in rectTransforms)
                {
                    if (item != null)
                    {
                        if (clampHeight)
                        {
                            item.sizeDelta = new Vector2(item.sizeDelta.x,Mathf.Clamp(rectTransform.sizeDelta.y + heightPadding, heightRange.x, heightRange.y) );
                        }
                        else
                        {
                            item.sizeDelta = new Vector2(item.sizeDelta.x, rectTransform.sizeDelta.y + heightPadding);
                        }
                        
                    }
                }
            }
        }
        
#if UNITY_EDITOR
        private bool _isValidate;
        bool IUIBehaviourDriverElement.IsValidated => _isValidate;
        void OnValidate()
        {
            _isValidate = true;
        }
#endif
    }

}
